import { TemplateFile } from "@/api";
import { TreeDataType } from "@arco-design/web-react/es/Tree/interface";
import { FolderClose } from "@icon-park/react";
import _, { Dictionary } from "lodash";
const DictionaryIcon = <FolderClose theme="outline" size="16" />;

function setNodeChildren(
  nodeData: TreeDataType,
  dictionary: Dictionary<TemplateFile[]>
) {
  const node = nodeData.dataRef as TemplateFile;
  const childrens = dictionary[node.id];
  if (childrens == null) return;

  nodeData.children = [];
  for (const childNode of childrens) {
    const childNodeData: TreeDataType = {
      key: childNode.id,
      title: childNode.fileName,
      dataRef: childNode,
      icon: childNode.directory ? DictionaryIcon : null,
    };
    nodeData.children.push(childNodeData);
    if (childNode.directory) {
      setNodeChildren(childNodeData, dictionary);
    }
  }
}

export function toTreeData(data: TemplateFile[]) {
  if (_.isEmpty(data)) return [];

  const roots = data.filter((k) => k.parentId === "-1");
  const dictionary = _.groupBy(data, (k: TemplateFile) => k.parentId);
  const res: TreeDataType[] = [];
  for (const node of roots) {
    const nodeData: TreeDataType = {
      key: node.id,
      title: node.fileName,
      dataRef: node,
      icon: node.directory ? DictionaryIcon : null,
    };
    res.push(nodeData);
    setNodeChildren(nodeData, dictionary);
  }

  return res;
}
